package com.eqdd.yiqidian.ui.yiqixue.fragment;

import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;

import com.eqdd.yiqidian.CoolRefreshRecyclerViewFragmentCustom;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport;
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx;
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector;
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector;
import com.eqdd.yiqidian.base.BaseFragment;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.rebuild.HttpResultRows;
import com.eqdd.yiqidian.bean.rebuild.LearnArticleListBean;
import com.eqdd.yiqidian.bean.rebuild.LearnArticleListBean;
import com.eqdd.yiqidian.helper.mvchelper.ModelRx2DataSource;
import com.eqdd.yiqidian.helper.mvchelper.Rx2DataSource;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.JsonConverter;
import com.eqdd.yiqidian.ui.yiqixue.LearnSearchActivity;
import com.eqdd.yiqidian.ui.yiqixue.info.LearnArticleInfoActivity;
import com.eqdd.yiqidian.ui.yiqiyue.YueLabelListActivity;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okrx2.adapter.FlowableBody;
import com.shizhefei.mvc.MVCCoolHelper;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Flowable;
import io.rong.imkit.utils.RongDateUtils;

/**
 * @author吕志豪 .
 * @date 18-2-7  下午2:12.
 * Github :https://github.com/lvzhihao100
 * E-Mail：1030753080@qq.com
 * 简书 :http://www.jianshu.com/u/6e525b929aac
 */

public class FindArticleFragment extends BaseFragment {
    private CoolRefreshRecyclerViewFragmentCustom dataBinding;
    private SlimAdapterEx<LearnArticleListBean> slimAdapterEx;
    private int pageNum;
    private String query;
    private String field;
    private String url;
    private MVCCoolHelper<List<LearnArticleListBean>> mvcHelper;

    @Override
    public ViewDataBinding initBinding(LayoutInflater inflater) {
        return dataBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_cool_recycler_view, null, false);
    }

    @Override
    protected void initData() {
        if (slimAdapterEx == null) {
            String lectureGuid = getArguments().getString(Config.LECTURE_GUID);
            url = TextUtils.isEmpty(url) ? getArguments().getString(Config.URL) : url;
            dataBinding.recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
            //添加自定义分割线
            DividerItemDecoration divider = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL);
            dataBinding.recyclerView.addItemDecoration(divider);
            slimAdapterEx = SlimAdapterEx.create().register(R.layout.list_item_80, new SlimInjector<LearnArticleListBean>() {
                @Override
                public void onInject(LearnArticleListBean data, IViewInjector injector) {
                    injector.image(R.id.iv_head, data.getIphoto())
                            .text(R.id.stv_name, data.getUpname())
                            .text(R.id.tv_title, data.getTitle())
                            .gone(R.id.iv_option)
                            .gone(R.id.rl_bg)
                            .text(R.id.tv_depart, data.getCreateTime())
                            .image(R.id.iv_img, data.getImage())
                            .text(R.id.tv_content, data.getTextContent())
                            .visibility(R.id.iv_img, TextUtils.isEmpty(data.getImage().trim()) ? View.GONE : View.VISIBLE)
                            .text(R.id.tv_source, "易企学")
                            .gone(R.id.stv_msg)
                            .text(R.id.stv_look, "阅读:" + data.getBrowseCount())
                            .gone(R.id.stv_support)
                            .with(R.id.recyclerViewLabel, view -> {
                                if (data.getLabel() == null) {
                                    return;
                                }
                                RecyclerView recyclerViewLabel = (RecyclerView) view;
                                List<String> stringList = new ArrayList<>();
                                for (String s : data.getLabel().split(",")) {
                                    if (!TextUtils.isEmpty(s)) {
                                        stringList.add(s);
                                    }
                                }
                                recyclerViewLabel.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false));
                                SlimAdapterEx<String> slimAdapterExLabel = SlimAdapterEx.create().register(R.layout.list_item_74, new SlimInjector<String>() {
                                    @Override
                                    public void onInject(String data, IViewInjector injector) {
                                        injector.gone(R.id.iv_clear)
                                                .text(R.id.tv_content, data);
                                    }
                                }).attachTo(recyclerViewLabel).updateData(stringList);
                                ItemClickSupport.addTo(recyclerViewLabel)
                                        .setOnItemClickListener((recyclerView, position, v) -> {
                                            Bundle bundle = new Bundle();
                                            bundle.putInt(Config.POS, 3);
                                            bundle.putString(Config.FIELD, slimAdapterExLabel.getDataItem(position));
                                            startActivity(LearnSearchActivity.class, bundle);
                                        });
                            });

                }

            }).attachTo(dataBinding.recyclerView).updateData(new ArrayList());
            ItemClickSupport.addTo(dataBinding.recyclerView)
                    .setOnItemClickListener((recyclerView, position, v) -> {
                        Bundle bundle = new Bundle();
                        bundle.putInt(Config.ID, slimAdapterEx.getDataItem(position).getId());
                        startActivity(LearnArticleInfoActivity.class, bundle);
                    });
            ModelRx2DataSource<LearnArticleListBean> dataSource = new ModelRx2DataSource<>(new ModelRx2DataSource.OnLoadSource() {
                @Override
                public Flowable<List> loadSource(int page, Rx2DataSource.DoneActionRegister register) {
                    pageNum = page == 1 ? 0 : pageNum;
                    return OkGo.<HttpResultRows<LearnArticleListBean>>post(HttpConfig.BASE_URL + url)
                            .params("page", pageNum)
                            .params("para", query)
                            .params("label", field)
                            .params("lectureGuid", lectureGuid)
                            .params("type", "app")
                            .converter(new JsonConverter<HttpResultRows<LearnArticleListBean>>() {
                                @Override
                                public void test() {
                                    super.test();
                                }
                            }).adapt(new FlowableBody<>())
                            .flatMap(listResultBean -> {
                                pageNum = listResultBean.getItems().getPage();
                                if (listResultBean.getStatus() == 200) {
                                    return Flowable.just(listResultBean.getItems() == null ? new ArrayList<LearnArticleListBean>() : listResultBean.getItems().getRows());
                                } else {
                                    ToastUtil.showShort(listResultBean.getMsg());
                                    return Flowable.just(new ArrayList<>());
                                }
                            });
                }
            });
            mvcHelper = new MVCCoolHelper<>(dataBinding.coolRefreshView);
            mvcHelper.setDataSource(dataSource);
            mvcHelper.setAdapter(slimAdapterEx);
            if (!TextUtils.isEmpty(url)) {
                mvcHelper.refresh();
            }
        }
    }

    @Override
    protected void setView() {

    }

    @Override
    public void onClick(View v) {

    }

    public void refresh(CharSequence currentQuery) {
        query = (String) currentQuery;
        mvcHelper.refresh();
    }

    public void refresh(String url, CharSequence currentQuery) {
        this.url = url;
        query = (String) currentQuery;
        if (mvcHelper != null) {
            mvcHelper.refresh();
        }
    }

    public void filed(String url, String field) {
        this.url = url;
        this.field = field;
        if (mvcHelper != null) {
            mvcHelper.refresh();
        }
    }
}
